package com.tangly.common.shiro.jwt;

import com.tangly.module.remote.UCenterRemoteClient;
import com.tangly.common.shiro.AuthInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author tangly
 */
@Component(value = "jwtRealm")
@Slf4j
public class JWTRealm extends AuthorizingRealm {

    @Autowired
    private UCenterRemoteClient uCenterRemoteClient;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        AuthInfo userAuth = (AuthInfo) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(userAuth.getRoles());
        simpleAuthorizationInfo.addStringPermissions(userAuth.getPermissions());
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String jwt = (String) authenticationToken.getCredentials();
        // 解密获得username，用于和数据库进行对比
        Long userAuthId = JWTUtil.getUserAuthId(jwt);
        if (userAuthId == null) {
            throw new AuthenticationException("无效token");
        }
        AuthInfo userAuth = null;
        try {
            //调用用户授权中心验证token并获取相应权限信息
            userAuth = uCenterRemoteClient.getAuthInfo(jwt);
        } catch (Exception e) {
            log.error("远程获取用户信息失败", e);
        }

        if (userAuth == null) {
            throw new AuthenticationException("User didn't existed!");
        }

        if (!JWTUtil.verify(jwt, userAuthId, userAuth.getUserId(), userAuth.getPassword())) {
            throw new AuthenticationException("Username or password error");
        }

        return new SimpleAuthenticationInfo(userAuth, jwt, "my_realm");
    }
}